
import { _decorator, Component, Node, Sprite, Vec2, Vec3, Label, EventTouch } from 'cc';
import Action3dManager, { Action3d, ActionMngType } from '../../Script/Common/Action3dManager';
import GameData from '../../Script/Common/GameData';
import Loader from '../../Script/Common/Loader';
import PlayerData from '../../Script/Common/PlayerData';
import yyComponent from '../../Script/Common/yyComponent';
import { EventType } from '../../Script/GameSpecial/GameEventType';
import { GlobalEnum } from '../../Script/GameSpecial/GlobalEnum';
const { ccclass, property } = _decorator;

@ccclass('TrySkinUI')
export class TrySkinUI extends yyComponent {

    protected initSub() {
        this.initBtnNo();
        this.initBtnNoWeapon();
        this.initSkinItem();
        this.initTitleLabel();
        this.initWeaponItem();

    }
    protected resetSub() {
        this.resetBtnNo();
        this.resetBtnNoWeapon();
        this.resetSkinItem();
        this.resetTitleLabel();
        this.resetWeaponItem();
    }

    protected onEvents() {
        this.node.on(Node.EventType.TOUCH_END, this.onNodeTouchEnd, this);
        this.on(EventType.LevelEvent.stopJoy, this.onStopJoy, this);
    }

    public show() {
        this.node.active = true;
        this.reset();
        this.onEvents();
        this.showWeaponItem();
    }

    protected runNodeScaleAction(node: Node) {
        let s = 1;
        node.setScale(s, s, s);
        s += 0.05;
        let d = 0.8;
        let scale0 = Action3dManager.scaleTo(d, s, s, s);
        s -= 0.1;
        let scale1 = Action3dManager.scaleTo(d, s, s, s);
        let seq = Action3dManager.sequence(scale0, scale1);
        let repeat = Action3dManager.repeatForever(seq);
        Action3dManager.getMng(ActionMngType.UI).runAction(node, repeat);
    }

    //#region 武器选项
    @property(Node)
    protected weaponItems: Node[] = [];
    protected weaponDatas: { type: GlobalEnum.WeaponType, id: number }[] = [];
    protected initWeaponItem() {
        for (let i = this.weaponItems.length - 1; i >= 0; --i) {
            this.weaponItems[i].on(Node.EventType.TOUCH_START, () => {
                this.onClickWeapon(i);
            });
        }
    }
    protected resetWeaponItem() {
        this.weaponDatas = [];
        let actMng = Action3dManager.getMng(ActionMngType.UI);
        for (let i = this.weaponItems.length - 1; i >= 0; --i) {
            actMng.stopAllActions(this.weaponItems[i]);
            this.weaponItems[i].active = false;
        }
        this.weaponItems[0].parent.active = false;
    }
    protected showWeaponItem() {
        this.weaponItems[0].parent.active = true;
        //随机获取未解锁的武器，记录数据：
        let data = this.getTowWeaponData();
        data = this.randomArry(data);

        if (data.length > this.weaponItems.length) {
            let index0 = Math.round(Math.random() * this.weaponItems.length);
            data.splice(index0, 1);
        }
        let index = data.length - 1;
        if (index >= this.weaponItems.length) {
            index = this.weaponItems.length - 1;
        }
        this.weaponDatas = [];
        for (let i = 0; i <= index; ++i) {
            let d = data[i];
            this.weaponDatas.push({
                id: d["id"],
                type: d["goodsType"],
            });
            this.weaponItems[i].active = true;
            this.loadImage(d.goodsType + d.id, (img) => {
                this.weaponItems[i].children[0].getComponent(Sprite).spriteFrame = img;
            });
        }
        let animIndex = Math.floor(Math.random() * (index - 0.001)) + 1;
        this.runNodeScaleAction(this.weaponItems[animIndex]);

        this.setTitleLabel("请选择要使用的武器");
        this.showBtnNoWeapon();
    }
    protected hideWeaponItem() {
        this.weaponItems[0].parent.active = false;
    }
    protected weaponList = ["claw", "knife", "katana", "gun", "hunter", "captain", "trapper"];
    protected getTowWeaponData() {
        // let weaponListTemp = this.randomArry(this.weaponList);
        let weaponListTemp = this.weaponList;
        let out = [];
        for (let i = 0; i < weaponListTemp.length; i++) {
            let type = weaponListTemp[i];
            let goodsData = GameData.getData("GoodsData")["weapon"][type];
            let playerData = PlayerData.getData("gameData.WeaponSkin.owned")[type];
            if (playerData.length < goodsData["num"]) {
                let leng = goodsData["num"];
                //最后一个武器有特殊皮肤，放最前面
                if (playerData.indexOf(leng) >= 0) {
                    out.unshift(goodsData[leng]);
                }
                let numArry = [];
                for (let i = 0; i < leng - 1; i++) {
                    numArry.push(i + 1);
                }
                numArry = this.randomArry(numArry);
                for (let j = 0; j < numArry.length; j++) {
                    let index = playerData.indexOf(numArry[j]);
                    if (index >= 0) {
                        out.push(goodsData[numArry[j]]);
                    }
                }
            };
        }
        return out;
    }
    //选择武器
    protected onClickWeapon(index) {
        // this.emit(EventType.Common.SDKEvent.showVideo, {
        //     success: () => {
        //         this.tryWeapon(this.weaponDatas[index]);
        //     },
        // });
        this.tryWeapon(this.weaponDatas[index]);
    }
    //视频观看成功，试用该武器
    protected tryWeapon(data) {
        this.emit(EventType.Common.PlayerDataEvent.updatePlayerData, {
            attribute: "gameData.WeaponSkin.try",
            value: data,
            mode: "=",
            emit: false,
            save: false,
        });
        // this.startLevel();
        this.hideWeaponItem();
        this.hideBtnNoWeapon();
        this.showSkinItem();
        // setTimeout(() => {
        this.showBtnNo();
        // }, 1500);
    }
    //#endregion

    //#region 皮肤选项
    @property(Node)
    protected skinItems: Node[] = [];
    protected skinDatas: number[] = [];
    protected initSkinItem() {
        for (let i = this.skinItems.length - 1; i >= 0; --i) {
            this.skinItems[i].on(Node.EventType.TOUCH_START, () => {
                this.onClickSkin(i);
            });
        }
    }
    protected resetSkinItem() {
        let actMng = Action3dManager.getMng(ActionMngType.UI);
        for (let i = 1; i < this.skinItems.length; ++i) {
            actMng.stopAllActions(this.skinItems[i]);
            this.skinItems[i].active = false;
        }
        this.skinItems[0].parent.active = false;
    }
    protected showSkinItem() {
        this.skinItems[0].parent.active = true;

        let curSkin = PlayerData.getData("gameData.PlayerSkin.cur");
        this.loadImage("skin" + curSkin, (img) => {
            this.skinItems[0].children[0].getComponent(Sprite).spriteFrame = img;
        });
        this.skinDatas = [curSkin];

        let data = [];
        let owned = PlayerData.getData("gameData.PlayerSkin.owned");
        for (let i = 1; i <= 18; ++i) {
            if (owned.indexOf(i) < 0) {
                data.push(i);
            }
        }
        data = this.randomArry(data);
        let index = data.length - 1;
        if (index >= this.skinItems.length - 1) {
            index = this.skinItems.length - 1;
        }
        for (let i = 1; i <= index; ++i) {
            this.skinDatas.push(data[i]);
            this.skinItems[i].active = true;
            this.loadImage("skin" + data[i], (img) => {
                this.skinItems[i].children[0].getComponent(Sprite).spriteFrame = img;
            });
        }
        let animIndex = Math.floor(Math.random() * (index - 0.001)) + 1;
        this.runNodeScaleAction(this.skinItems[animIndex]);
        this.setTitleLabel("免费试用皮肤");
    }
    protected onClickSkin(index) {
        if (index > 0) {
            this.emit(EventType.Common.SDKEvent.showVideo, {
                success: () => {
                    this.trySkin(this.skinDatas[index]);
                },
                fail: () => {

                },
            });
        } else {
            this.trySkin(this.skinDatas[index]);
        }
    }
    protected trySkin(id) {
        this.emit(EventType.Common.PlayerDataEvent.updatePlayerData, {
            attribute: "gameData.PlayerSkin.try",
            value: id,
            mode: "=",
            emit: false,
            save: false,
        });
        this.startLevel();
    }

    //#endregion

    //#region 提示标题
    @property(Label)
    protected titleLabel: Label = null;
    protected initTitleLabel() {
        this.titleLabel.string = "";
    }
    protected resetTitleLabel() {
        this.titleLabel.string = "";
    }
    protected setTitleLabel(str: string) {
        this.titleLabel.string = str;
    }
    //#endregion

    //#region 跳过武器选择按钮
    @property(Node)
    protected btnNoWeapon: Node = null;
    protected initBtnNoWeapon() {
        this.btnNoWeapon.active = false;
    }
    protected resetBtnNoWeapon() {
        this.btnNoWeapon.active = false;
    }
    protected showBtnNoWeapon() {
        this.btnNoWeapon.active = true;
    }
    protected hideBtnNoWeapon() {
        this.btnNoWeapon.active = false;
    }
    //#endregion

    //#region 取消试用皮肤按钮
    @property(Node)
    protected btnNo: Node = null;
    protected initBtnNo() {
        this.btnNo.active = false;
    }
    protected resetBtnNo() {
        this.btnNo.active = false;
    }
    protected hideBtnNo() {
        this.btnNo.active = false;
    }
    protected showBtnNo() {
        this.btnNo.active = true;
    }
    //#endregion

    //将arr数组随机乱序
    protected randomArry(arr) {
        let leng = arr.length;
        let numArry = [];
        for (let i = 0; i < leng; i++) {
            numArry.push(i);
        }
        let outArry = [];
        for (let i = 0; i < leng; i++) {
            let index = Math.floor(Math.random() * (numArry.length - 0.001));
            let index2 = numArry.splice(index, 1)[0];
            outArry.push(arr[index2]);
        }
        return outArry;
    }
    protected loadImage(name: string, cb?: Function) {
        Loader.loadBundleRes("UI", "Image/shop/skin/" + name + "/spriteFrame", (res) => {
            if (!!cb) {
                cb.call(this, res);
            }
        });
    }

    //开始关卡
    protected startLevel() {
        this.hideUI(GlobalEnum.UI.trySkin);
        this.emit(EventType.LevelEvent.decideWeaponSkin);
    }

    protected onBtnNo() {
        this.playClickBtn();
        this.startLevel();
    }

    protected onBtnNoWeapon() {
        this.hideWeaponItem();
        this.hideBtnNoWeapon();
        this.showSkinItem();
        // setTimeout(() => {
            this.showBtnNo();
        // }, 1500);
    }

    protected onStopJoy(p: Vec2) {
        if (p.y < 320) {
            this.emit(EventType.Common.HeyGameSDK.clickNativeAd);
        }
    }

    protected onNodeTouchEnd(e: EventTouch) {
        let p = e.getUILocation();
        this.onStopJoy(p);
    }
}

